package com.harunasan.carrental.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.harunasan.carrental.api.common.domain.entity.BaseInitUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis自动填充字段
 * @author liangyi
 */
@Slf4j
@Component
public class UserMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (metaObject.getOriginalObject() instanceof BaseInitUserEntity) {
//                if (StpUtil.getLoginId() != null && this.getFieldValByName("createdId", metaObject) == null) {
//                    this.setFieldValByName("createdId", StpUtil.getLoginId(), metaObject);
//                }
                this.strictInsertFill(metaObject, "createdTime", LocalDateTime.class, LocalDateTime.now());
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("非http请求的插入");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (metaObject.getOriginalObject() instanceof BaseInitUserEntity) {
                BaseInitUserEntity baseUserEntity = (BaseInitUserEntity) metaObject.getOriginalObject();
                if (baseUserEntity.getIsDeleted() == null) {
//                    if (StpUtil.getLoginId() != null) {
//                        this.setFieldValByName("deletedId", StpUtil.getLoginId(), metaObject);
//                    }
                    this.strictUpdateFill(metaObject, "deletedTime", LocalDateTime.class, LocalDateTime.now());
                } else {
//                    if (StpUtil.getLoginId() != null) {
//                        this.setFieldValByName("updatedId", StpUtil.getLoginId(), metaObject);
//                    }
                    this.strictUpdateFill(metaObject, "updatedTime", LocalDateTime.class, LocalDateTime.now());
                }
            }
        } catch (Exception e) {
            //log.error("非http请求的更新");
        }
    }
}
